package cn.clq.basic.controller;

import cn.clq.basic.exception.BusinessException;
import cn.clq.basic.util.AjaxResult;
import cn.clq.basic.util.FastdfsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author clqlongbao
 * @version 1.0
 * @description: fastdfs的接口
 * @date 2022/6/13 0:04
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    /*文件上传的接口*/
    @PostMapping("/upload")
    //意思是必须传一个k为“file”的文件过来
    public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            String filename = file.getOriginalFilename();//文件全路径
            String extName = filename.substring(filename.lastIndexOf(".") + 1);//文件扩展名

            String path = FastdfsUtil.upload(file.getBytes(), extName);//文件的相对路径
            return AjaxResult.me().setResultObj(path);
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件上传失败"+e.getMessage());
        }
    }


    /*文件删除的接口*/
    @DeleteMapping
    public AjaxResult delete(@RequestParam String path){//  /group1/M00/00/07/CgAIC2KmHiSAB50xAAH8WEvl_l0687.jpg
        try {
            String pathTmp = path.substring(1);//   group1/M00/00/07/CgAIC2KmHiSAB50xAAH8WEvl_l0687.jpg
            String groupName = pathTmp.substring(0,pathTmp.indexOf("/"));// group1
            String fileName = pathTmp.substring(pathTmp.indexOf("/")+1);//  M00/00/07/CgAIC2KmHiSAB50xAAH8WEvl_l0687.jpg
            FastdfsUtil.delete(groupName,fileName);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件删除失败"+e.getMessage());
        }
    }
}
